package com.fms.model.messaging;

import com.fms.model.ILogger;
import com.fms.model.messaging.domain.DraftMessage;
import com.fms.model.messaging.domain.IEmailData;
import com.fms.model.messaging.repo.IEmailDataRepository;

/**
 * An implementation of an email service that 
 * organizes the information for use by the
 * messager service.
 * 
 * A translation between the input mechanisms of
 * the IEmailData interface and the DraftMessage
 * needed by the messager.
 * 
 * @author johnsba1
 *
 */
public class MessageDispatcher implements IEmailService
{
	private IEmailData	data;
	private IMessager	messager;
	private IEmailDataRepository	repo;
	private ILogger	logger;

	/**
	 * Creates a dispatcher that pulls data from the
	 * email data repository and sends the information
	 * to the messager
	 * 
	 * @param _messager
	 * @param _repo
	 */
	public MessageDispatcher(IMessager _messager,
							 IEmailDataRepository _dataRepo, 
							 ILogger _logger)
	{
		this.data = _dataRepo.load();
		this.messager = _messager;
		this.repo = _dataRepo;
		this.logger = _logger;
	}

	/* 
	 * Performs the translation between the email data and the
	 * message.
	 * (non-Javadoc)
	 * @see com.fms.model.domain.messaging.IEmailService#sendMail()
	 */
	public void sendMail()
	{
		DraftMessage message = new DraftMessage();
		message.setTo(data.getDestinations());
		message.setMessage(data.getMessage());
		message.setSheet(data.getFlowSheet());
		message.setSubject(data.getSubject());

		try
		{
			messager.send(message);
		}
		catch(Exception e)
		{
			logger.log(e.getMessage());
		}
		
		
		repo.save(data);
	}

}
